package com.nutiteq.mapper.forms;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import com.nutiteq.MapComponent;
import com.nutiteq.components.ZoomRange;
import com.nutiteq.mapper.MapScreen;

public class SetZoomLevel extends Form implements CommandListener {
  public static final Command SET_ZOOM_LEVEL = new Command("Set zoom", Command.ITEM, 0);
  private final MapScreen mapScreen;
  private final MapComponent mapDisplay;
  private final TextField zoomLevel;

  private final Command set;
  private final Command back;
  private final ZoomRange validZoomRange;
  private final int previousZoom;

  public SetZoomLevel(final MapScreen mapScreen, final MapComponent mapDisplay) {
    super("Set zoom level");
    this.mapScreen = mapScreen;
    this.mapDisplay = mapDisplay;

    validZoomRange = mapDisplay.getZoomRange();
    previousZoom = mapDisplay.getZoom();

    zoomLevel = new TextField("New zoom level (" + validZoomRange.getMinZoom() + "-"
        + validZoomRange.getMaxZoom() + ")", "" + previousZoom, 2, TextField.ANY);
    append(zoomLevel);

    set = new Command("Set zoom", Command.OK, 0);
    back = new Command("Back", Command.BACK, 0);

    addCommand(set);
    addCommand(back);

    setCommandListener(this);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == back) {
      mapScreen.show(mapScreen);
    } else {
      final int nextZoom = parseZoom(zoomLevel.getString());
      mapDisplay.setZoom(nextZoom);
      mapScreen.show(mapScreen);
    }
  }

  private int parseZoom(final String string) {
    int result = previousZoom;
    try {
      result = Integer.parseInt(string);
    } catch (final NumberFormatException e) {
      result = previousZoom;
    }

    return result >= validZoomRange.getMinZoom() && result <= validZoomRange.getMaxZoom() ? result
        : previousZoom;
  }
}
